import cache from '../api/cache'
const app = getApp();

/**
 * 检查用户是否已授权
 */
function checkAuth() {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          resolve(true);
        } else {
          resolve(false);
        }
      },
      fail(err) {
        reject(err);
      }
    });
  });
}

/**
 * 获取用户信息
 */
function getUserInfo() {
  return new Promise((resolve, reject) => {
    wx.getUserInfo({
      success(res) {
        resolve(res.userInfo);
      },
      fail(err) {
        reject(err);
      }
    });
  });
}

/**
 * 登录授权
 */
function login() {
  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        if (res.code) {
          resolve(res.code);
        } else {
          reject(new Error('登录失败'));
        }
      },
      fail(err) {
        reject(err);
      }
    });
  });
}

/**
 * 检查并获取用户信息
 */
async function checkAndGetUserInfo() {
  const isAuth = await checkAuth();
  if (!isAuth) {
    // 未授权，引导用户授权
    await authorize();
  }
  return await getUserInfo();
}

/**
 * 引导用户授权
 */
function authorize() {
  return new Promise((resolve, reject) => {
    wx.authorize({
      scope: 'scope.userInfo',
      success() {
        resolve();
      },
      fail(err) {
        reject(err);
      }
    });
  });
}
// utils/auth.js

async function loginAndGetUserInfo(that) {
  try {
    const code = await login();
    const userInfo = await checkAndGetUserInfo();
    var baseUrl = app.globalData.baseUrl;
    // 将 code 和 userInfo 发送到服务器
    wx.request({
      url: baseUrl + '/xq/login',
      method: 'POST',
      data: {
        code: code,
        userInfo: userInfo
      },
      success(res) {
        console.log('登录成功:', res.data);

        if (result.data.errorCode == 200) {
          cache.setOp(app.globalData.userCacheKey, result.data.data)
          // cache.setOp(app.globalData.tokenKey, result.data.data["token"])
          // app.globalData.token = result.data.data["token"]
          app.globalData.key = result.data.data["key"]
          that.setData({
            user: result.data.data,
            hasUserInfo: true
          })
          // 跳转到指标页
          wx.hideLoading()
          that.setData({
            'listShowFlag': true
          })
        } else {
          wx.hideLoading()
          that.setData({
            "iosDialog2": true
          })
          console.log('服务器异常')
        }
      },
      fail(err) {
        console.error('登录失败:', err);
      }
    });
  } catch (err) {
    console.error('登录失败:', err);
  }
}

module.exports = {
  checkAuth,
  getUserInfo,
  login,
  checkAndGetUserInfo,
	authorize,
	loginAndGetUserInfo
};